import React from 'react'
import {Table} from 'antd'

export default class TableDemo extends React.Component{
    state={
        data:[
            {
              name: '张三',
              age:22,
            },
            {
              name: '王五',
              age: 25,
            },
            {
              name: '王五',
              age:22,
            },
            {
              name: '张三',
              age: 22,
            },
            {
              name: '李四',
              age: 22,
            },
            {
              name: '李四',
              age: 33,
            },
        ]
    }
    //整理数据
    createNewArr=data=>{
        data=data.map((d,i)=>({...d,key:i,}))
        data=data.reduce((result, item) => {
            //首先将name字段作为新数组result取出
            if (result.indexOf(item.name) < 0) {
                result.push(item.name)
            }
            return result
        }, []).reduce((result, name) => {
            //将name相同的数据作为新数组取出，并在其内部添加新字段**rowSpan**
            const children = data.filter(item => item.name === name);
            result = result.concat(
                children.map((item, index) => ({
                    ...item,
                    rowSpan: index === 0 ? children.length : 0,//将第一行数据添加rowSpan字段
                }))
            )
            return result;
        }, [])
        return data
    }
    getColumns=()=>{
        const columns = [
            {
                title: '名字',
                dataIndex: 'name',
                key: 'name',
                render(_, row) {
                    return {
                        children: row.name,
                        props: {
                            rowSpan: row.rowSpan,
                        }
                    }
                }
            },
            {
                title: '年龄',
                dataIndex: 'age',
                key: 'age',
            },
        ]
        return columns;
    }
    render(){
        const {data}=this.state
        return (
            <div className="tableDemo">
                <Table columns={this.getColumns()} dataSource={this.createNewArr(data)} bordered/>
            </div>
        )
    }
}